<template>
  <div>
    <el-form :model="value" :label-width="lw" ref="form">
      <el-form-item
        v-for="(item, key) in options"
        :key="key"
        :prop="key"
        :rules="item.rules"
        :label="showlabel ? item.title : undefined"
      >
        <!-- 生成input框 -->
        <el-input
          v-model="value[key]"
          :type="item.type"
          :maxlength="item.max"
          :disabled="item.dis"
          :style="item.style"
          :placeholder="item.ph"
          v-if="item.tag === 'input'"
        ></el-input>

        <!-- 生成计算器 -->
        <InputNumber
          v-else-if="item.tag === 'number'"
          v-model="value[key]"
          :min="item.min"
          :max="item.max"
          :label="item.label"
          :step="item.step"
          :placeholder="item.ph"
          :style="item.style"
          :disabled="item.dis"
        ></InputNumber>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { deepClone } from "uti/common";
import { InputNumber } from "element-ui";
/**
 * 是否为数字
 */
const isNumber = (value) => typeof value === "number";
export default {
  name: "Form",
  components: { InputNumber },
  mounted() {
    const { validate, clearValidate } = this.$refs.form;
    Object.assign(this, { validate, clear: clearValidate });
  },
  computed: {
    /**
     * 处理后的表单配置
     */
    options() {
      const options = deepClone(this.opts);
      for (const key in options) {
        if (Object.hasOwnProperty.call(options, key)) {
          const item = options[key];

          item.tag = item.tag || "input";
          item.type = item.type || "text";
          item.rules = item.rules || [];

          if (item.required) {
            item.rules.unshift({ required: true });
          }

          for (const rule of item.rules) {
            if (rule.message) {
              continue;
            }
            if (rule.required) {
              rule.message = item.title + "不能为空";
            } else if (isNumber(rule.min) && isNumber(rule.max)) {
              rule.message = `${item.title}长度为${rule.min}到${rule.max}`;
            } else if (isNumber(rule.min)) {
              rule.message = `${item.title}的最小长度为${rule.min}`;
            } else if (isNumber(rule.max)) {
              rule.message = `${item.title}的最大长度为${rule.max}`;
            }
          }
        }
      }
      return options;
    },
  },
  props: {
    /**
     * 显示ladal
     */
    showlabel: {
      type: Boolean,
      default: true,
    },
    /**
     * 绑定的值
     */
    value: {
      type: Object,
      default: () => {},
    },
    /**
     * 表单配置项
     */
    opts: {
      type: Object,
      required: true,
      default: () => {},
    },
    /**
     * label的宽度
     */
    lw: {
      type: String,
      default: "90px",
    },
  },
};
</script>

<style>
</style>